#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()


from celery import shared_task
from django.conf import settings
import datetime
from random import randint

from vouchers.models import *
from customers.utils import AlipayOpen, pay_transactions_jsapi, pay_transactions_native, favor_distributed_coupons, favor_query_coupons, favor_meituan_coupons, favor_query_coupons_sichun, favor_distributed_coupons_sichun
from activities.models import Channel


@shared_task
def distribute_couponbag(data):
    '''派发券包'''
    filp_id = data['filp_id']
    instance = CustomizeActivityFlipCARDS.objects.get(id=filp_id)
    customizeactivity = instance.customizeactivity
    customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
    user = instance.user
    today = datetime.datetime.now()
    if instance.open_status == 2:
        for customizeactivityrules in customizeactivityrules_set:
            alidiscountcoupon = customizeactivityrules.alidiscountcoupon
            for i in range(customizeactivityrules.count):
                if alidiscountcoupon.coupon_channel == 1:
                    pass
                elif alidiscountcoupon.coupon_channel == 2:
                    out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                    if alidiscountcoupon.platform_id == 13:
                        distribute_channel = Channel.objects.get(id=13)
                    else:
                        distribute_channel = Channel.objects.get(id=9)
                    data_json = {
                        "stock_id": alidiscountcoupon.template_id,
                        "out_request_no": out_biz_no,
                        "appid": appid,
                        "stock_creator_mchid": alidiscountcoupon.platform.mchid
                    }
                    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                    if 'code' in data_dict:
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_create': today,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'status': 14,
                            'return_msg': data_dict['message'],
                            'appid': appid
                        }
                        voucherinfo = AliDiscountCouponInfo.objects.create(**defaults)
                    else:
                        while True:
                            activity_id = alidiscountcoupon.id
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count + 1
                            activity_new_remain_number = activity_origin_remain_number - 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        coupon_id = data_dict['coupon_id']
                        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'voucher_id': coupon_id,
                            'user_id': openid,
                            'template_id': result['stock_id'],
                            'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                            'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                            'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                            'gmt_create': today,
                            'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                            'name': result['coupon_name'],
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'appid': appid
                        }
                        if today < datetime.datetime.strptime(defaults['gmt_active'], "%Y-%m-%d %H:%M:%S"):
                            defaults['status'] = 11
                        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=defaults, voucher_id=coupon_id)
                    datail_data = {}
                    datail_data['flipcard_id'] = instance.id
                    datail_data['alidiscountcouponinfo_id'] = voucherinfo.id
                    CustomizeActivityFlipCARDSDetail.objects.get_or_create(defaults=datail_data, flipcard_id=instance.id, alidiscountcouponinfo_id=voucherinfo.id)
                elif alidiscountcoupon.coupon_channel == 5:
                    out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                    meituan_result = favor_meituan_coupons(out_biz_no, alidiscountcoupon.template_id, user.mobile)
                    if meituan_result['status'] != 'success':
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_create': today,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'status': 14,
                            'return_msg': meituan_result['errorMsg'],
                            'appid': appid
                        }
                        voucherinfo = AliDiscountCouponInfo.objects.create(**defaults)
                    else:
                        while True:
                            activity_id = alidiscountcoupon.id
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count + 1
                            activity_new_remain_number = activity_origin_remain_number - 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        coupon_id = meituan_result['data'][0]['code']
                        gmt_create = datetime.datetime.now()
                        alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                            gmt_active = gmt_create
                        else:
                            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                            gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'voucher_id': coupon_id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_active': gmt_active,
                            'gmt_expired': gmt_expired,
                            'total_amount': alidiscountcoupon.amount,
                            'gmt_create': today,
                            'available_amount': alidiscountcoupon.amount,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'appid': appid
                        }
                        if today < datetime.datetime.strptime(defaults['gmt_active'], "%Y-%m-%d %H:%M:%S"):
                            defaults['status'] = 11
                        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=defaults, voucher_id=coupon_id)
                    datail_data = {}
                    datail_data['flipcard_id'] = instance.id
                    datail_data['alidiscountcouponinfo_id'] = voucherinfo.id
                    CustomizeActivityFlipCARDSDetail.objects.get_or_create(defaults=datail_data, flipcard_id=instance.id, alidiscountcouponinfo_id=voucherinfo.id)
                else:
                    pass
        instance.open_status = 4
        instance.save()


if __name__ == '__main__':
    pass
